﻿# encoding=utf-8
import sys
import os
import telnetlib
from time import sleep
import threading

# 配置选项  
HOST = 'your host' # Telnet服务器IP  
USERNAME = 'your username'   # 登录用户名  
PASSWORD = 'your password'  # 登录密码  
PORT = 23
TIMEOUT = 10
FINISH = '$ '      # 命令提示符  
COMMANDS = ['echo "test"']  # 用户需要的命令列表，会依次执行
PRE_TIME = 1    #指令列表间隔时间
    
class UeTelnet():
    def __init__(self, _host, _username, _password, _port, _timeout):
        self.host = _host
        self.username = _username
        self.password = _password
        self.port = _port
        self.timeout = _timeout

    def Connect(self):
        try:
            print "Connecting"
            self.telnetob = telnetlib.Telnet(self.host, port=self.port, timeout=self.timeout)  
            self.telnetob.set_debuglevel(0)
            if not self.username == "": # 如果没有填写用户名则按照没有验证来登录
                return self.UserLogin()
            else:
                print "user is null, no encryption"
                if self.telnetob.read_until(FINISH):
                    return True
        except Exception,e:
            print e.message
            self.telnetob.close()
            return
            
    def UserLogin(self):
        # 输入登录用户名
        self.telnetob.read_until('login: ')
        self.telnetob.write(self.username + '\n')
        # 输入登录密码
        self.telnetob.read_until('Password: ')
        self.telnetob.write(self.password + '\n')
        # 判断是否登录成功,出现$标志，证明登录成功，否则失败
        # 6s的超时，验证失败将抛出异常
        cond = threading.Event()
        time = threading.Timer(1, self.EventSet, args=(cond,))
        time.setDaemon(True)
        time.start()
        cond.wait(5)
        # print cond.isSet()
        if cond.isSet():
            print "login successful"
            time.cancel()
            return True
        else:
            print "login erro"
            return False

    def EventSet(self, cond):
        self.telnetob.read_until(FINISH)
        cond.set()

    def DoAction(self, commands):
        # 登录完毕后执行命令
        for command in commands:
            self.telnetob.write('%s\n' % command)
            print self.telnetob.read_until(FINISH)


if __name__=='__main__':  
    ueTelent = UeTelnet(HOST, USERNAME, PASSWORD, PORT, TIMEOUT)
    if (ueTelent.Connect() == 1):
        print "start cmd"
        while True:
            ueTelent.DoAction(COMMANDS)
            sleep(PRE_TIME)
    else:
        ueTelent.telnetob.close()
        exit()

        